<template>
  <!-- 新增与删除 -->
  <div class="authorityOperation">
    <el-card>
      <el-form
        ref="form"
        :rules="addRules"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            style="max-width: 260px"
            placeholder="请填写用户名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          v-if="pageType === 'edit' ? false : true"
        >
          <el-input
            type="password"
            v-model="formData.password"
            style="max-width: 260px"
            placeholder="请填写密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmpassword"
          v-if="pageType === 'edit' ? false : true"
        >
          <el-input
            type="password"
            v-model="formData.confirmpassword"
            style="max-width: 260px"
            placeholder="请确认密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="formData.name"
            style="max-width: 260px"
            placeholder="请填写姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            style="max-width: 260px"
            placeholder="请填写邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="formData.mobile"
            style="max-width: 260px"
            placeholder="请填写手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <template slot-scope="scope">
            <div class="avatar_wrap">
              <el-upload
                :class="{ 'avatar-uploader': !headimgurl }"
                style="height: 40px;"
                :action="uploadFileURL"
                accept="image/jpeg,image/gif,image/png"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="headimgurl" :src="headimgurl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="权限" prop="role_id">
          <el-select
            v-model="formData.role_id"
            placeholder="请选择权限"
            style="width: 260px"
          >
            <el-option
              v-for="item in roleData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教师类型" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择教师类型"
            style="width: 260px"
          >
            <el-option
              v-for="item in teacherType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { changeTitleMinin } from "@/mixin";
import { uploadFileURL } from "@/utils/url";
import http from "@/api/teacher";
export default {
  name: "authorityOperation",
  mixins: [changeTitleMinin],
  data() {
    var checkData = (rules, value, callback) => {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          callback(new Error("不能包含汉字"));
        } else if (value.length < 4) {
          callback(new Error("用户名要大于四位字符"));
        } else {
          callback();
        }
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 3) {
        callback(new Error("密码不得少于3位字符"));
      } else {
        if (this.formData.confirmpassword != "") {
          this.$refs.form.validateField("confirmpassword");
        }
        callback();
      }
    };
    var confirmpassword = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请再次输入密码"));
      } else if (value == undefined) {
        callback();
      } else if (value != this.formData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var rules = {
      username: [
        { required: true, message: "请填写用户名" },
        { validator: checkData, trigger: "blur" }
        // { pattern: /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g, message: '用户名不能为汉字', trigger: 'blur' }
      ],
      name: [{ required: true, message: "请填写姓名" }],

      confirmpassword: [{ validator: confirmpassword, trigger: "blur" }],
      email: [
        { required: true, message: "请填写邮箱" },
        {
          pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
          message: "邮箱填写有误",
          trigger: "blur"
        }
      ],
      mobile: [
        { required: true, message: "请填写手机号" },
        { pattern: /^1[3-9]\d{9}$/, message: "手机号填写有误", trigger: "blur" }
      ],
      role_id: [{ required: true, message: "请选择权限" }],
      type: [{ required: true, message: "请选择教师类型" }],
      status: [{ required: true, message: "请选择状态" }]
    };
    return {
      formData: {
        status: 1
      },
      rules: {
        ...rules
      },
      addRules: {
        ...rules,
        password: [
          { required: true, message: "请输入密码" },
          { validator: validatePass, trigger: "blur" }
        ],
        confirmpassword: [
          { required: true, message: "请确认密码" },
          { validator: confirmpassword, trigger: "blur" }
        ]
      },
      isAdd: true,
      roleData: [],
      teacherType: [],
      headimgurl: null,
      uploadFileURL,
      pageType: null
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log("res, file:", res, file);
      this.formData["headimgurl"] = res.data;
      this.headimgurl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isPicture =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isPicture) {
        this.$message.error("上传头像图片只能是图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isPicture && isLt2M;
    },

    handleCancel() {
      this.$router.go(-1);
    },
    handleSubmit() {
      console.log("this.formData:", this.formData);
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.formData));
          if (this.isAdd) {
            formData.center_id = JSON.parse(
              sessionStorage.getItem("user")
            ).center_id;
            http.createContent(formData).then(res => {
              this.$message.success(res.msg || "新增成功！");
              this.$router.push({ name: "authorityList" });
            });
          } else {
            http.editContent(formData).then(res => {
              this.$message.success(res.msg || "编辑成功！");
              this.$router.push({ name: "authorityList" });
            });
          }
        }
      });
    },
    getContentDetail(id) {
      http.getContentDetail({ id }).then(res => {
        let formData = res.data;
        if (formData.password) {
          formData.password = "";
        }
        this.headimgurl = formData.headimgurl;
        this.formData = formData;
      });
    },
    getPageParams() {
      if (Object.keys(this.$route.params).length) {
        sessionStorage.setItem(
          "authorityOperationParams",
          JSON.stringify(this.$route.params)
        );
      }

      let pageParams = sessionStorage.getItem("authorityOperationParams");
      if (pageParams) {
        pageParams = JSON.parse(pageParams);
        this.isAdd = pageParams.pageType == "create" ? true : false;
        this.pageType = pageParams.pageType;
        if (pageParams.id) {
          this.getContentDetail(pageParams.id);
        }

        //权限管理 进来
        if (pageParams.role_id) {
          this.formData["role_id"] = pageParams.role_id;
        }
      }
    },

    getRole() {
      http.getRole().then(res => {
        this.roleData = res.data;
      });
    },

    getTeacherType() {
      let params = { varname: "teacher_type" };
      http.getTeacherType(params).then(res => {
        this.teacherType = res.data;
      });
    }
  },
  created() {
    this.getRole();
    this.getTeacherType();
    this.getPageParams();
  }
};
</script>

<style lang="scss" scoped>
.authorityOperation {
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    cursor: pointer;
    background: #f1f1f1;
  }

  &::-moz-scrollbar {
    display: none;
  }
  &::-ms-scrollbar {
    display: none;
  }
  &::-o-scrollbar {
    display: none;
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    width: 10px;
    cursor: pointer;
    background: #bbb;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    border-radius: 0px;
    background: #f1f1f1;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 16px;
    color: #8c939d;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  .el-upload--text {
    height: 100%;
  }
  .avatar_wrap {
    width: 218px;
    height: 100%;
    .avatar {
      border-radius: 100%;
      width: 40px;
      height: 40px;
      cursor: pointer;
    }
    .avatar-uploader {
      height: 40px;
    }
  }
}
</style>
